package com.muk.meis.controller.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * Servlet implementation class UploadFileController
 */
@WebServlet("/UploadFileController")
@MultipartConfig
public class UploadFileController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadFileController() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	private String getFileName(Part part) {
		String partHeader = part.getHeader("content-disposition");
		for (String cd : part.getHeader("content-disposition").split(";")) {
			if (cd.trim().startsWith("filename")) {
				return cd.substring(cd.indexOf('=') + 1).trim()
						.replace("\"", "");
			}
		}
		return null;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String percode = request.getParameter("percode");
		for (Part part : request.getParts()) {
			InputStream is = request.getPart(part.getName()).getInputStream();
			int i = is.available();
			byte[] b = new byte[i];
			is.read(b);
			System.out.println("************* 1 "+part.getName());
			String fileName = getFileName(part);
			if(fileName == null) continue;
			String fileNameWrite = getServletContext().getRealPath("/")
					+ "data" + File.separator + percode + File.separator
					+ fileName;
			System.out.println("************* 2 "+fileNameWrite);
			FileOutputStream os = new FileOutputStream(fileNameWrite);
			os.write(b);
			is.close();
		}
		response.sendRedirect(request.getContextPath()+"/school/listnews.jsp?percode="+percode+"#tabs-2");
	}

}
